package com.wy.controller;

import com.wy.pojo.Code;
import com.wy.service.CodeService;
import com.wy.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * description CodeController
 * author wy
 * date 2021-09-02 22:31
 **/
@Slf4j
@RestController
@RequestMapping("/code")
public class CodeController
{
    @Autowired
    private CodeService codeService;

    @Reference(check = false)
    private EmailService emailService;

    /**
     * ⽣成验证码并发送到对应邮箱，成功true，失败false
     * @param email
     */
    @GetMapping("/create/{email}")
    public boolean createCode(@PathVariable String email) {
        String format = String.format("%04d", new Random().nextInt(1000));
        log.info("发送验证码：{}", format);
        boolean b = emailService.sendCode(email, format);
        if (b) {
            codeService.addCode(email, format);
            return true;
        }
        return false;
    }

    /**
     * 校验验证码是否正确，0正确1错误2超时
     * @param email
     * @param code
     */
    @GetMapping("/validate/{email}/{code}")
    public Integer validateCode(@PathVariable String email, @PathVariable String code) {
        Code codeByEmail = codeService.getCodeByEmail(email);
        if (codeByEmail != null && codeByEmail.getCode().equals(code)) {
            return 0;
        }
        return 1;
    }
}
